#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <linux/i2c-dev.h>

//bus:1
#define I2C_DEV "/dev/i2c-4"

void hex_dump( unsigned char *values, int count ){
	while( count-- > 0 ){
		printf( "%02x ", *(values++) );
	}
}


int main( int argc, char* argv[] ){

	const char *cmd = argv[1];
	const char *value = argv[2];
	
	if( !cmd ){
		cmd = "read";
		value = "10";
	}
	if( !value )
		value = "10";
	
	int i2c = open( I2C_DEV, O_RDWR );
	if( i2c<0 ){
		fprintf( stderr, "Can't Open %s.\n", I2C_DEV );
		return 1;
	}
	int oled_addr = -1;
	if( strcmp( cmd, "read" )==0 ){
		oled_addr = 0x3c;
	}
	if( strcmp( cmd, "write" )==0 ){
		oled_addr = 0x3d;
	}


	
#if 0

	if( strcmp( cmd, "read" )==0 ){
		int count_to_read = atoi(value);
		unsigned char buff[count_to_read]={0xff};
		int count = read( i2c, buff, count_to_read );
		printf("Readed:%d.\n", count );
		hex_dump( buff, count );printf( "\n" );
		return 0;
	}
	
	if( strcmp( cmd, "write")==0 ){
		int count_to_write = strlen(value);
		unsigned char buff[count_to_write+1];
		buff[0] = 0x40;
		memcpy(  buff+1, value, count_to_write );
		int count = write( i2c, buff, count_to_write + 1 );
		printf("Writed:%d.\n", count);
		return 0;
	}
	
#endif
#if 0

	if( strcmp( cmd, "read" )==0 ){
		unsigned char buff[64]={0};
		int count = i2c_smbus_read_block_data( i2c, 0x40, buff );
		printf("Readed:%d.\n", count );
		hex_dump( buff, count );printf( "\n" );
		return 0;
	}
	
	if( strcmp( cmd, "write")==0 ){
		int count_to_write = strlen(value);
		int count = i2c_smbus_write_block_data( i2c, 0x40, count_to_write, value );
		printf("Writed:%d.\n", count);
		return 0;
	}
	

#endif

#if 1

	if( strcmp( cmd, "read" )==0 ){
		int ret;
		if( ioctl( i2c, I2C_SLAVE, 0x3c )!=0 ){
			fprintf( stderr, "Can't set slave device's address to %x.\n", 0x3c );
			exit(1);
		}
		ret = i2c_smbus_write_byte( i2c, 0x40 );
		if( ret<0 ){
			fprintf( stderr, "aaaaaa" );
			exit(1);
		}
		if( ioctl( i2c, I2C_SLAVE, 0x3c )!=0 ){
			fprintf( stderr, "Can't set slave device's address to %x.\n", 0x3d );
			exit(1);
		}
		ret = i2c_smbus_read_byte( i2c );
		if( ret<0 ){
			fprintf( stderr, "bbbbbb" );
			exit(1);
		}
		printf( "Read byte is %d(0x%2x).\n", ret, ret );
	
	}

	if( strcmp( cmd, "write" )==0 ){
		unsigned char byte;
		int ret;
		if( ioctl( i2c, I2C_SLAVE, 0x3c )!=0 ){
			fprintf( stderr, "Can't set slave device's address to %x.\n", 0x3c );
			exit(1);
		}
		ret = i2c_smbus_write_byte( i2c, 0x40 );
		if( ret<0 ){
			fprintf( stderr, "aaaaaa" );
			exit(1);
		}
		if( ioctl( i2c, I2C_SLAVE, 0x3d )!=0 ){
			fprintf( stderr, "Can't set slave device's address to %x.\n", 0x3d );
			exit(1);
		}
		ret = i2c_smbus_write_byte( i2c, atoi(value) );
		if( ret<0 ){
			fprintf( stderr, "bbbbbb" );
			exit(1);
		}
		
	
	}

	close( i2c );
#endif

	return 0;
}

